const Service = require('egg').Service;
const axios = require('axios');
const crypto = require('crypto');
const dayjs = require("dayjs");

class AliPaypalService extends Service {

  // Generate signature according to Antom documentation
  generateSignature(method, path, clientId, requestTime, body = '') {
    const message = `${method} ${path}\n${clientId}.${requestTime}.${body}`;
    const privateKey = this.config.antom.privateKey;
    const sign = crypto.createSign('SHA256');
    sign.update(message);
    const signature = sign.sign(privateKey, 'base64');
    const encodedSignature = encodeURIComponent(signature);

    // Format signature header according to specification
    return `algorithm=RSA256, keyVersion=${this.config.antom.keyVersion || '1'}, signature=${encodedSignature}`;
  }

  // Create PayPal order
  async createOrder(orderData) {
    try {
      /**
       * 请求地址 https://open-na-global.alipay.com/ams/api/v1/payments/createPaymentSession
       */

      const path = '/ams/api/v1/payments/createPaymentSession';
      const clientId = this.config.antom.clientId;
      const requestTime = new Date().getTime().toString();
      const bodyStr = JSON.stringify(orderData);

      // Generate signature
      const signature = this.generateSignature('POST', path, clientId, requestTime, bodyStr);
      const { data } = await axios({
        method: 'POST',
        url: `${this.config.antom.url}${path}`,
        headers: {
          'Content-Type': 'application/json; charset=UTF-8',
          'Signature': signature,
          'client-id': clientId,
          'request-time': requestTime,
        },
        data: orderData
      });
      if (data.result.resultCode !== 'SUCCESS') {
        return {
          success: false,
          error: data.result
        };
      }
      return {
        success: true,
        data: {
          ...data,
          orderData
        }
      };
    } catch (error) {
      this.ctx.logger.error('PayPal Create Order Error:', error);
      return {
        success: false,
        error: error.response?.data?.message || error.message
      };
    }
  }


  async notify(data) {
    if (data.notifyType === 'PAYMENT_RESULT') {
      console.log(data, '支付成功')
      await this.payCallback(data)
    } else if (data.notifyType === 'CAPTURE_RESULT') {
      console.log(data, '请款成功')
      await this.captureCallback(data)
    } else if (data.notifyType === 'REFUND_RESULT') {
      console.log(data, '退款成功')
      await this.refundCallback(data)
    }
    return {
      "result": {
        "resultCode": "SUCCESS",
        "resultMessage": "Success",
        "resultStatus": "S"
      }
    }
  }

  // 支付回调
  async payCallback(data) {
    if (data.result.resultCode !== 'SUCCESS') {
      return {
        "result": {
          "resultCode": "ERROR",
          "resultMessage": "ERROR",
          "resultStatus": "U"
        }
      }
    }
    let captureData = {
      "captureAmount": data.paymentAmount,
      "captureRequestId": data.paymentRequestId,
      "paymentId": data.paymentId
    }
    this.ctx.service.order.update(data.paymentRequestId, {
      status: 1,
      payment_status: 'paid',
      pay_detail: data,
      pay_time: data.paymentTime,
      alipay_payment_id: data.paymentId,
      alipay_success_detail: data,
      alipay_capture_detail: captureData,
    });
    this.capture(captureData)
    // TODO发送订单邮件
    this.ctx.service.email.sendEmail({
      id: data.paymentRequestId
    })
  }
  // 请款回调
  async captureCallback(data) {
    let requestData =  {
      alipay_capture_success_detail: data,
      alipay_capture_id: data.captureId,
      amount_status: 1,
      amount_status_name: '请款成功'
    }
    if (data.result.resultCode !== 'SUCCESS') {
      requestData.amount_status = 0
      requestData.amount_status_name = '请款失败'
    }
    await this.ctx.service.order.update(data.captureRequestId, requestData);
    return {
      "result": {
        "resultCode": "SUCCESS",
        "resultMessage": "Success",
        "resultStatus": "S"
      }
    }
  }
  // 退款回调
  async refundCallback(data) {
    if (data.result.resultCode !== 'SUCCESS') {
      return {
        "result": {
          "resultCode": "ERROR",
          "resultMessage": "ERROR",
          "resultStatus": "U"
        }
      }
    }
    this.ctx.service.order.update(data.refundRequestId, {
      alipay_refund_success_detail: data,
      status: 2, // 已退款状态
      payment_status: 'refunded',
      refund_time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      refund_id: data.refundId
    });

    return {
      "result": {
        "resultCode": "SUCCESS",
        "resultMessage": "Success",
        "resultStatus": "S"
      }
    }
  }
  /**
   * 请款
   * https://open-na-global.alipay.com/ams/sandbox/api/v1/payments/capture
   */
  async capture(captureData) {
    try {
      const path = '/ams/sandbox/api/v1/payments/capture';
      const clientId = this.config.antom.clientId;
      const requestTime = new Date().getTime().toString();
      const bodyStr = JSON.stringify(captureData);

      // Generate signature
      const signature = this.generateSignature('POST', path, clientId, requestTime, bodyStr);
      axios({
        method: 'POST',
        url: `${this.config.antom.url}${path}`,
        headers: {
          'Content-Type': 'application/json; charset=UTF-8',
          'Signature': signature,
          'client-id': clientId,
          'request-time': requestTime,
        },
        data: captureData
      })
      return {
        success: true,
      };
    } catch (error) {
      console.log('请款失败:', error);
      this.ctx.logger.error('请款失败:', error);
      return {
        success: false,
      }
    }
  }


  /**
   * 退款
   * https://open-na-global.alipay.com/ams/api/v1/payments/refund
   * https://open-na-global.alipay.com/ams/sandbox/api/v1/payments/refund
   */
  async refund(data) {
    const order = await this.ctx.service.order.findOne(data.orderId)
    if (!order) {
      throw new Error('Order in Empty')
    }
    let refundData = {
      paymentId: order.alipay_payment_id,
      refundRequestId: order.id,
      refundAmount: {
        currency: "AUD",
        value: parseInt(data.amount * 100).toString()
      },
      refundReason: data.note,
      refundNotifyUrl: `this.config.antom.clientUrl/api/payment/alipay/notify`
    }
    console.log('refundData',refundData)
    const path = '/ams/sandbox/api/v1/payments/refund';
    const clientId = this.config.antom.clientId;
    const requestTime = new Date().getTime().toString();
    const bodyStr = JSON.stringify(refundData);

    // Generate signature
    const signature = this.generateSignature('POST', path, clientId, requestTime, bodyStr);
    const refundRes = await axios({
      method: 'POST',
      url: `${this.config.antom.url}${path}`,
      headers: {
        'Content-Type': 'application/json; charset=UTF-8',
        'Signature': signature,
        'client-id': clientId,
        'request-time': requestTime,
      },
      data: refundData
    })
    if (refundRes.data) {
      if (refundRes.data.result.resultCode === 'SUCCESS') {
        this.ctx.model.Order.update({
          alipay_refund_detail: refundData,
          refund_amount: data.amount,
          refund_remark: data.note
        }, {
          where: {
            id: data.orderId
          }
        })
        return  {
          success: true,
        }
      } else {
        throw new Error(refundRes.data.result.resultMessage)
      }
    } else {
      throw new Error('refund Fail!')
    }
  }
}

module.exports = AliPaypalService;
